package com.github.smartheye.fabric.common.util;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.PrivateKey;
import java.util.HashSet;
import java.util.Set;

import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import com.github.smartheye.fabric.common.crypto.PEMUtil;
import com.github.smartheye.fabric.common.user.FabricUser;
import com.github.smartheye.fabric.common.user.UserEnrollment;

public class UserUtil {

	public static String readString(InputStream in) throws IOException {
		BufferedInputStream br = new BufferedInputStream(in);
		byte[] bytes = new byte[br.available()];
		br.read(bytes);
		br.close();
		return new String(bytes);
	}

	public static FabricUser loadUser(String privateKeyPath, String signCertsPath) throws IOException {
		ResourceLoader loader = new DefaultResourceLoader();
		Resource privateKeyResource = loader.getResource(privateKeyPath);
		Resource signcertsResource = loader.getResource(signCertsPath);

		// 载入PeerAdmin用户的私钥
		String privateKeyStr = readString(privateKeyResource.getInputStream());
		// 载入PeerAdmin用户的证书
		String certificateStr = readString(signcertsResource.getInputStream());
		// 从私钥文件（PEM）获取PrivateKey
		PrivateKey privateKey = PEMUtil.privateKeyFromPEM(privateKeyStr);
		// 创建用户
		UserEnrollment enrollment = new UserEnrollment(privateKey, certificateStr);

		FabricUser user = new FabricUser();
		user.setName("Admin");
		user.setAccount("Admin");
		user.setMspId("Org1MSP");
		user.setEnrollment(enrollment);
		Set<String> roleset = new HashSet<String>();
		roleset.add("Admin");
		user.setRoles(roleset);
		return user;
	}
}
